package com.sikaryofficial.workbench.utils.excel.converter.goods;

import cn.hutool.core.util.NumberUtil;
import com.alibaba.excel.converters.Converter;
import com.alibaba.excel.converters.ReadConverterContext;
import com.alibaba.excel.converters.WriteConverterContext;
import com.alibaba.excel.enums.CellDataTypeEnum;
import com.alibaba.excel.metadata.data.ReadCellData;
import com.alibaba.excel.metadata.data.WriteCellData;
import com.sikaryofficial.common.core.utils.StringUtils;
import com.sikaryofficial.workbench.domain.eo.PriceTierEO;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 价格区间转换器
 * 只负责数据转换，不做业务逻辑处理
 */
public class PriceTierConverter implements Converter<List<PriceTierEO>> {

    /**
     * 多个价格全局的分隔符
     * 100_200_15.2;200_300_15.3
     */
    private static final String SEPARATOR = "[;；]";

    private static final String LINK_SYMBOL = "_";
    /**
     * 匹配价格区间字符串.eg：
     * 100-200-15.2
     */
    private static final Pattern PATTERN = Pattern.compile("\\s*(\\d*)\\s*" + LINK_SYMBOL + "\\s*(\\d*)\\s*" + LINK_SYMBOL + "\\s*([\\d.]*)\\s*");

    @Override
    public Class<?> supportJavaTypeKey() {
        return List.class;
    }

    @Override
    public CellDataTypeEnum supportExcelTypeKey() {
        return CellDataTypeEnum.STRING;
    }

    @Override
    public List<PriceTierEO> convertToJavaData(ReadConverterContext<?> context) throws Exception {
        ReadCellData<?> readCellData = context.getReadCellData();
        String stringValue = readCellData.getStringValue();

        List<PriceTierEO> priceTierEOList = new ArrayList<>();
        String[] split = stringValue.split(SEPARATOR);
        for (String tierStr : split) {
            if (tierStr == null || tierStr.trim().isEmpty()) {
                continue;
            }
            Matcher matcher = PATTERN.matcher(tierStr);
            if (matcher.matches()) {
                String min = matcher.group(1);
                String max = matcher.group(2);
                String unitPrice = matcher.group(3);

                PriceTierEO priceTierEO = new PriceTierEO();
                priceTierEOList.add(priceTierEO);
                priceTierEO.setMinQuantity(NumberUtil.parseInt(min, null));
                priceTierEO.setMaxQuantity(NumberUtil.parseInt(max, null));
                if (StringUtils.isNotEmpty(unitPrice)) {
                    priceTierEO.setUnitPrice(new BigDecimal(unitPrice));
                }

            } else {
                throw new IllegalArgumentException("价格区间解析失败：" + tierStr);
            }
        }

        return priceTierEOList;
    }

    @Override
    public WriteCellData<?> convertToExcelData(WriteConverterContext<List<PriceTierEO>> context) throws Exception {
        List<PriceTierEO> priceTierEOList = context.getValue();
        if (priceTierEOList == null || priceTierEOList.isEmpty()) {
            return new WriteCellData<>("");
        }

        StringBuilder sb = new StringBuilder();
        for (PriceTierEO priceTierEO : priceTierEOList) {
            sb.append(Objects.toString(priceTierEO.getMinQuantity(), ""))
                    .append(LINK_SYMBOL).append(Objects.toString(priceTierEO.getMaxQuantity(), ""))
                    .append(LINK_SYMBOL).append(Optional.ofNullable(priceTierEO.getUnitPrice()).map(BigDecimal::toPlainString).orElse(""))
                    .append(";");
        }
        return new WriteCellData<>(sb.toString());
    }

}
